import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { enquireScreen, unenquireScreen } from 'enquire-js';

import styles from './TableList.less';

Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "Y+": this.getUTCFullYear(),
    "M+": this.getMonth() + 1, //月份
    "D+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'success'];
const status = ['未使用', '已使用'];

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  return (
    <Modal
      title="新建规则"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述">
        {form.getFieldDecorator('desc', {
          rules: [{ required: true, message: 'Please input some description...' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
    </Modal>
  );
});

let isMobile;
enquireScreen(b => {
  isMobile = b;
});

@connect(({ rule, loading }) => ({
  rule,
  loading: loading.models.rule,
}))
@Form.create()
export default class AccountArticleList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    account_id:0,
    isMobile:false,
    selectDate:"",
  };

  componentDidMount() {
    this.enquireHandler = enquireScreen(mobile => {
      this.setState({
        isMobile: mobile,
      });
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'rule/fetchPubAccounts',
    });
    this.refresh()
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      account_id: this.state.account_id,
      date: this.state.selectDate,
    };

    dispatch({
      type: 'rule/fetchAccountArticles',
      payload: params,
    });
  };


  refresh = () => {
    const { dispatch } = this.props;
    const { rule: { accountArticle:{ page,page_size }}} = this.props;

    dispatch({
      type: 'rule/fetchAccountArticles',
      payload: {
        page:page,
        size:page_size,
        account_id: this.state.account_id,
        date: this.state.selectDate,
      },
    });
  }

  praseType = value => {
    switch(value){
      case 'BAIJIA':
        return "百家"
      case 'TOUTIAO':
        return "头条"
      case 'QIER':
        return "企鹅"
      case 'DAYU':
        return "大鱼"
    }
  }

  praseDate = value => {
    var date = new Date(value)
    date.setHours(date.getHours()-8)
    var s = date.Format('YYYY-MM-DD HH:mm:ss')
    return s
  }

  handleChange = value => {
    this.state.account_id = value
    this.setState({
      account_id: value,
    })

    const { dispatch } = this.props;
    dispatch({
      type: 'rule/fetchAccountArticles',
      payload: {
        page:1,
        size:10,
        account_id: this.state.account_id,
        date: this.state.selectDate,
      },
    });
  }

  onChange = (date, dateString) => {
    this.state.selectDate = dateString
    this.refresh()
  }

  render() {
    // praseType = this.praseType
    const { rule: { accountArticle,pubAccounts }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;
    
    var columns;
    if (isMobile){
      columns = [
        {
          title: '标题',
          dataIndex: 'title',
          width: 380,
          render: (val,record) => <a href={record.url} target="_Blank">{record.title}</a>,
        },
        {
          title: '账号名称',
          width: 90,
          dataIndex: 'account_name',
          render: val => <span>{val}</span>,
        },
        {
          title: '平台',
          dataIndex: 'plat',
          width: 70,
          render: (val,record) => <span>{this.praseType(record.plat)}</span>,
        },
        {
          title: '推荐',
          width: 75,
          dataIndex: 'recomment_count',
          render: val => <span>{val}</span>,
        },
        {
          title: '阅读',
          width: 75,
          dataIndex: 'read_count',
          render: val => <span>{val}</span>,
        },
        {
          title: '评论',
          width: 50,
          dataIndex: 'comment_count',
          render: val => <span>{val}</span>,
        },
        {
          title: '发布时间',
          width: 95,
          dataIndex: 'time',
          render: val => <span>{this.praseDate(val).substring(3,14)}</span>,
        }]
    }else{

      columns = [
      {
        title: '标题',
        dataIndex: 'title',
        render: (val,record) => <a href={record.url} target="_Blank">{record.title}</a>,
      },
      {
        title: '账号名称',
        width: 100,
        dataIndex: 'account_name',
        render: val => <span>{val}</span>,
      },
      {
        title: '平台',
        dataIndex: 'plat',
        width: 75,
        render: (val,record) => <span>{this.praseType(record.plat)}</span>,
      },
      {
        title: '推荐',
        width: 75,
        dataIndex: 'recomment_count',
        render: val => <span>{val}</span>,
      },
      {
        title: '阅读',
        width: 75,
        dataIndex: 'read_count',
        render: val => <span>{val}</span>,
      },
      {
        title: '评论',
        width: 60,
        dataIndex: 'comment_count',
        render: val => <span>{val}</span>,
      },
      {
        title: '收藏',
        width: 60,
        dataIndex: 'fav_count',
        render: val => <span>{val}</span>,
      },
      {
        title: '发布时间',
        width: 95,
        dataIndex: 'time',
        render: val => <span>{this.praseDate(val)}</span>,
      },
      {
        title: '更新时间',
        dataIndex: 'update_time',
        width: 95,
        render: val => <span>{this.praseDate(val)}</span>,
      }
    ];
  }

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
    };

    var listAccountsOption = () => {
      var res = [];
      res.push(<Option key={key} value={0} >全部账号</Option>)
      for(var key in pubAccounts){
        res.push(<Option key={key} value={pubAccounts[key].id} >{this.praseType(pubAccounts[key].plat)}-{pubAccounts[key].nick_name}</Option>)
      }
      return res
    }

    return (
      <div  style={{ margin: '0 -46px 0' }}>
        <Card bordered={false}>
          <div className={styles.tableList}>
          <div className={styles.tableListOperator}>
          <Select defaultValue="全部账号" style={{ width: 180 }} onChange={this.handleChange}>
            {listAccountsOption()}
          </Select>
          <DatePicker style={{ marginLeft: '20px' }} onChange={this.onChange} />
          </div>

            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={accountArticle}
              columns={columns}
              pagination={true}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </div>
    );
  }
}
